package board_mvc.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import board.BoardDBBean;
import board.BoardDataBean;

@Controller
public class ListAction implements CommandHandler {
	@Resource( name="instance" )
	BoardDBBean dao;
	
	@RequestMapping("/list")
	@Override
	public ModelAndView process(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String,Object>map=new HashMap<String,Object>();
		int pageSize=5;
		int pageBlock=3;
		int count = 0;
		
		String pageNum = null;
		int currentPage = 0;
		int start = 0;
		int end = 0;
		int number = 0;
		int pageCount = 0;
		int startPage = 0;
		int endPage = 0;
	
		count = dao.getCount();
		
		pageNum = request.getParameter( "pageNum" );
			
		if( pageNum == null ) {
			pageNum = "1";
		}
		
		currentPage = Integer.parseInt( pageNum );

		pageCount = ( count / pageSize ) + ( count % pageSize > 0 ? 1 : 0 );
		
		if( currentPage > pageCount ) currentPage = pageCount;
		
		start = ( currentPage - 1 ) * pageSize + 1;			// ( 5 -1 ) * 10 + 1		41
		end = currentPage * pageSize;							// 5 * 10					50
		
		number = count - ( currentPage -1 ) * pageSize;	// 50 - ( 2 - 1 ) * 10
		
		startPage = ( currentPage / pageBlock ) * pageBlock + 1;	// ( 9 / 10 ) * 10 + 1 	1
		
		if( currentPage % pageBlock == 0 ) startPage -= pageBlock;
		
		endPage = startPage + pageBlock - 1;							// 1 + 10 - 1			10
		
		if( endPage > pageCount ) endPage = pageCount;

		if(count>0){
			Map <String, Integer> listmap = new HashMap<String, Integer>();
			listmap.put( "start", start );
			listmap.put( "end", end );		
			
			List <BoardDataBean> list = dao.getArticles( listmap );
			map.put("list", list);
		}
		
		map.put("count", count);
		map.put("pageNum", pageNum);
		map.put("currentPage", currentPage);
		map.put("pageCount", pageCount);
		map.put("number", number);
		map.put("startPage", startPage);
		map.put("endPage", endPage);
		map.put("pageBlock", pageBlock);
		
		return new ModelAndView("list",map);
	}
}
